import pyecharts
from pyecharts.charts import Map, Geo, Timeline, Line, Tab, Bar
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
from datetime import date, datetime
import webbrowser
import json
import pandas as pd
import datetime
import numpy as np
# 读取数据
update_date = date.today()
def load(path):
    '''
    根据路径加载数据
    :param path:对应路径
    '''
    with open(path, encoding="utf-8") as fp:
        data = json.load(fp)
    return data

area_data_timeline = load("data/metadata/area_data_day.json")

def get_value(dic, key):
    try:
        return dic[key]
    except KeyError:
        return 0

all_data_timeline = load("data/metadata/DXYOverall.json")


def insert_data(to_update_date, to_update_area, dic, is_city):
    if to_update_date in format_data:
        if to_update_area in format_data[to_update_date]:
            pass
        else:
            format_data[to_update_date][to_update_area] = {}
    else:
        format_data[to_update_date] = {}
        format_data[to_update_date][to_update_area] = {}
    format_data[to_update_date][to_update_area]['currentConfirmedCount'] = get_value(dic, 'currentConfirmedCount')
    format_data[to_update_date][to_update_area]['confirmedCount'] = get_value(dic, 'confirmedCount')
    format_data[to_update_date][to_update_area]['deadCount'] = get_value(dic, 'deadCount')
    format_data[to_update_date][to_update_area]['suspectedCount'] = get_value(dic, 'suspectedCount')
    format_data[to_update_date][to_update_area]['curedCount'] = get_value(dic, 'curedCount')
    format_data[to_update_date][to_update_area]['countryName'] = get_value(dic, 'countryName')
    # 用于区分区域层级
    if is_city:
        format_data[to_update_date][to_update_area]['is_city'] = 1
    else:
        format_data[to_update_date][to_update_area]['is_city'] = 0
format_data = {}
for item in area_data_timeline['results'][::-1]:
    to_update_date = date.fromtimestamp(item['updateTime'] / 1000)
    to_update_area = item['provinceShortName']
    insert_data(to_update_date, to_update_area, item, 0)
    if 'cities' in item:
        if item['cities']:
            for city_data in item['cities']:
                insert_data(to_update_date, city_data['cityName'], city_data, 1)

for item in all_data_timeline[::-1]:
    to_update_date = date.fromtimestamp(item['updateTime'] / 1000)
    insert_data(to_update_date, '全国', item, 0)

time_range = list(format_data.keys())
tl = Timeline(init_opts=opts.InitOpts(theme='dark', width='400'))
tl.add_schema(axis_type='time', is_auto_play=True, is_timeline_show=False)

for day in time_range:
    geo = (
            Geo(init_opts=opts.InitOpts(theme='dark'))
            .add_schema(maptype="china", zoom=1)
            .add("累计确诊人数", 
                 [(key_, value_['confirmedCount']) for key_, value_, in format_data[day].items() 
                  if key_ in pyecharts.datasets.COORDINATES.keys() and value_['is_city']==1], 
                 type_='heatmap',
                 symbol_size=3,
                 progressive=50)
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="新型冠状病毒全国疫情热力图【自动轮播】",
                                         subtitle="更新日期：{}".format(update_date)),
                legend_opts=opts.LegendOpts(is_show=False),
                visualmap_opts=opts.VisualMapOpts(max_=50000, is_show=False, 
                                                  is_piecewise=True,
                                                  pieces=[{"min": 50000}, 
                                                          {"min": 5000, "max": 50000},
                                                          {"min": 500, "max": 5000},
                                                          {"min": 10, "max": 500},
                                                          {"max": 10} ],
                                                  range_color=['blue', 'green', 'green', 'yellow', 'red']),
                graphic_opts=[opts.GraphicGroup(
                                                graphic_item=opts.GraphicItem(
                                                    rotation=JsCode("Math.PI / 4"),
                                                    bounding="raw",
                                                    right=110,
                                                    bottom=110,
                                                    z=100,
                                                ),
                                                children=[
                                                    opts.GraphicRect(
                                                        graphic_item=opts.GraphicItem(
                                                            left="center", top="center", z=100
                                                        ),
                                                        graphic_shape_opts=opts.GraphicShapeOpts(
                                                            width=400, height=50
                                                        ),
                                                        graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                                                            fill="rgba(0,0,0,0.3)"
                                                        ),
                                                    ),
                                                    opts.GraphicText(
                                                        graphic_item=opts.GraphicItem(
                                                            left="center", top="center", z=100
                                                        ),
                                                        graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                                            text=day,
                                                            font="bold 26px Microsoft YaHei",
                                                            graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                                                                fill="#fff"
                                                            ),
                                                        ),
                                                    ),
                                                ],
                                            )
                                ],
            )
    )

    tl.add(geo, day)

tl.render_notebook()